<?php

	class UploadMediaCommand implements ICommand
	{
		public function execute($event)
		{
			if (count($_FILES) == 0)
			{
				throw new Exception('There is no file to upload!');
			}
			
			$file 		= 	$_FILES['media'];
			$name 		= 	$event->data['name'];
			$ref 		= 	$event->data['ref'];
			$folder_id 	= 	$event->data['folder'];
			
			$folders 	= 	EbModel::getModel('Media','MediaFolder')->selectById($folder_id);
			
			if (count($folders) == 0)
			{
				throw new Exception('The destination folder is not found!');
			}
			
			$folder_path		= 	EbModel::getModel('Media','MediaFolder')->getFolderPath($folder_id);
						
			// Get extension
			$extension_name 	= 	EbFilesToolkit::getExtension($file['name']);
			$extension_model 	= 	EbModel::getModel('Media','MediaExtension');
			$extensions			=	$extension_model->selectByName($extension_name);

			if (count($extensions) == 0)
			{
				throw new Exception('The extension '.$extension_name.' is unknown of the system!');
			}
			
			// Upload the file to the right provider
			$extension 		= $extensions[0];
			$folder 		= $folders[0];
			$provider		= new Media_HttpProvider(ROOT,'/',$folder_path);
			$media_item_code = $provider->getCode($extension_name);
			
			if ($provider->upload($file['tmp_name'],$media_item_code) === false)
			{
				throw new Exception('The file cannot be uploaded!');
			}
			
			$media 				= (object) array('name' => $name, 'fd_id' => $folder_id);
			$media_item_model 	= EbModel::getModel('Media','MediaItem');
			
			// If "Add Media"
			if (!isset($event->data['media']))
			{
				$media_id 			= EbModel::getModel('Media','Media')->insert($media);
			
				$mainfile = (object) array('name' => $file['name'],'pr_id' => 1,'type' => 1, 'md_id' => $media_id,'ex_id' => $extension->ex_id,'code' => $media_item_code);
					
				$media_item_model->insert($mainfile);
			
				EbController::dispatchEvent(new Event('Media/GenerateImageThumbnail',array('media' => $media_id,'folder' => $folder_id)));
			}
			else
			{
				// If "Add Media Item"
				$media_item = (object) array('name' => $file['name'], 'uuid' => $uuid,'pr_id' => 1,'type' => 3, 'md_id' => $event->data['media'],'ex_id' => $extension->ex_id,'code' => $media_item_code);
					
				$media_item_model->insert($media_item);
			}

			return new Event('redirect',$ref);
		}
	}